package com.wzdigit.wms.common.utils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;

/**
 * Base64加密、解密
 * 
 * @author 26833
 *
 */
public class Base64Util {

	public static String encode(String agr0) {
		try {
			Encoder encoder = Base64.getEncoder();
			return encoder.encodeToString(agr0.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException ex) {
			ex.printStackTrace();
		}
		return null;
	}

	public static byte[] encode(byte[] agr0) {
		Encoder encoder = Base64.getEncoder();
		return encoder.encode(agr0);
	}

	public static String decode(String agr0) {
		try {
			Decoder decoder = Base64.getMimeDecoder();
			byte[] result = decoder.decode(agr0);
			return new String(result, "UTF-8");
		} catch (UnsupportedEncodingException ex) {
			ex.printStackTrace();
		}
		return null;
	}

	public static String HMACSHA256(String data, String key) throws Exception {

		Mac sha256_HMAC = Mac.getInstance("HmacSHA256");

		SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");

		sha256_HMAC.init(secret_key);

		byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));

		StringBuilder sb = new StringBuilder();

		for (byte item : array) {

			sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));

		}

		return sb.toString().toUpperCase();

	}
}
